package com.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.payment.config.AlipayConfig;
import com.payment.entity.Pay;
import com.payment.service.ArrangeService;
import com.payment.service.PayService;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@RestController
@RequestMapping("/alipay")
public class PayController {
    @Resource
    private PayService payService;

    //支付接口 支付完请查询是否支付成功
    @RequestMapping("/pay/{orderId}/{cost}") // 订单id（ 不能重复）和消费金额
    public void pay(@PathVariable String orderId,@PathVariable String cost, HttpServletResponse response){
        try {
            AlipayClient alipayClient = AlipayConfig.getAlipayClient();
            // 设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            AlipayTradePayModel model = new AlipayTradePayModel();
            // 设定订单号 必须要写,且订单号不能重复
            model.setOutTradeNo(orderId);
            // 设置订单金额
            model.setTotalAmount(cost);
            // 订单名字
            model.setSubject("患者挂号订单");
            // 订单描述
            model.setBody("患者挂号支付订单");
            // 产品码
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            // 设置参数
            alipayRequest.setBizModel(model);
            // 设置回调地址
              String url = "http://localhost:5173/#/pay";
                          System.out.println(url);
                          alipayRequest.setReturnUrl(url);

            String result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询支付状态接口
     *
     * 传订单号(随机字母+随机数字) 和病人id即可
     */
    @GetMapping("/query/{orderId}/{patientsId}")
    public ResponseEntity<ResDTO> queryPayStatus(@PathVariable String orderId,@PathVariable int patientsId) {
        try {
            // 初始化支付宝客户端
            AlipayClient alipayClient = AlipayConfig.getAlipayClient();
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{\"out_trade_no\":\"" + orderId + "\"}");

            // 调用支付宝查询接口
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                // 查询成功
                String tradeStatus = response.getTradeStatus(); // 获取交易状态
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    // 支付成功，处理支付逻辑
                    Pay pay = new Pay();
                    pay.setOrderNumber(orderId);
                    pay.setPayCost(response.getTotalAmount()); // 从查询结果中获取金额
                    pay.setPayWay("支付宝");
                    pay.setPayState(1); // 1 表示支付成功
                    pay.setPatientsId(patientsId);
                    //创建时间
                    pay.setCreateDate(java.time.LocalDateTime.now().toString());

                    payService.add(pay);

                    return ResponseEntity.ok(ResDTO.success(orderId,patientsId,null));
                } else {
                    return ResponseEntity.ok(ResDTO.error("支付失败！"));
                }
            } else {
                return ResponseEntity.ok(ResDTO.error("支付失败！"));
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return ResponseEntity.ok(ResDTO.error("查询失败！"));
        }
    }

    @GetMapping("/getAll")
    public ResponseEntity<ResDTO> getAll(){
        List<Pay> _list= payService.getAll();
        if (_list!=null){
            return ResponseEntity.ok(ResDTO.success(_list));
        }
        return ResponseEntity.ok(ResDTO.error());
    }




}